var db = require('../db/index.js').get();
var utils = require('../utils.js');
// console.log(utils);
var imageCl = db.image, configCl = db.config;

async function init() {
    var failed = [];
    var q = {
        $or: [
            { 'baseInfo.aHash_8_d_md5': { $ne: utils.K.HASH8.md5 } },
            { 'baseInfo.bHash_8_d_md5': { $ne: utils.K.HASH8.md5 } },
            { 'baseInfo.aHash_8_d': { $exists: false } },
            { 'baseInfo.aHash_8_d_md5': { $exists: false } },
            { 'baseInfo.bHash_8_d': { $exists: false } },
            { 'baseInfo.bHash_8_d_md5': { $exists: false } },
        ]
    };
    var c = await imageCl.countDocuments(q);
    for (var i = 0; i < c; i++) {
        var img;
        try {
            var s = Date.now();
            img = (await imageCl.find(q).skip(failed.length).limit(1))[0];
            img.baseInfo.aHash_8_d = utils.K.HASH8.arr.map(x => utils.distanceOf(x, img.baseInfo.aHash_8));
            img.baseInfo.bHash_8_d = utils.K.HASH8.arr.map(x => utils.distanceOf(x, img.baseInfo.bHash_8));
            img.baseInfo.aHash_8_d_md5 = img.baseInfo.bHash_8_d_md5 = utils.K.HASH8.md5;
            img.markModified('baseInfo.aHash_8_d');
            img.markModified('baseInfo.bHash_8_d');
            await img.save();
            console.log('set di for', img._id, i, '--', c,
                '->\n\t',
                img.baseInfo.aHash_8_d.join(', '),
                '\n\t',
                img.baseInfo.bHash_8_d.join(', '),
                "\n\t::", Date.now() - s + 'ms'
            );
        } catch (e) {
            console.log('failed', i, '--', c, e.message);
            failed.push({i, _id: img ? img._id : null, Error: e.message});
            await img && img.save();
        }
    }
    return failed;
}

if (!module.parent) {
    init()
} else {
    module.exports = {
        init
    };
}